<script setup>
import {get_wb,delete_wb} from  "@/axios/weibo";
import {computed, onMounted, reactive, ref, watch} from "vue";
import {useRouter} from 'vue-router';
import WeiboInfo from "@/components/weiboInfo.vue";
import {closeToast, showLoadingToast, showNotify, showSuccessToast} from "vant";
import router from "@/router/index.js";
import {uploadStore} from "@/stores/UploadStorage.js";

const upLoad = uploadStore()

onMounted(()=>{

})

const wbData =  reactive({
  records:[]
})


const common = reactive({
  size: 12,
  current:0,
  total:0,
  pages:0,
  refresh:false,
  deleteId:String
})



const loading = ref(false);
const finished = ref(false);
const search = reactive({
  //按钮load
  searchNow: false,
  //搜索表单开关
  formShow:false,
  //日历选择框开关
  dateShow:false,
  contnet:null,
  minDate:new Date('2023-08-01'),
  maxDate: new Date(),
  start:null,
  end:null,
  date:null
})

const isSearch = ref( false);

const dateHandle = (values)=>{
  const [start, end] = values;
  search.start = `${formatDate(start)}`;
  search.end = `${formatDate(end)}`;
  search.dateShow = false;
  search.date = `${formatDate(start)} - ${formatDate(end)}`;
}



const formatDate = (date) => `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;

const initParam = (code) =>{
  let param = {}
  param.size = common.size;
  if(code === 200){
    param.current = common.current + 1;
  }
  param.content = search.contnet.replace(/\s+/g, '')
  param.startTime = search.start
  param.endTime = search.end
  return param;
}

const searchRsetRefresh = ()=>{
  searchRset()
  // search.searchNow = true;
  // finished.value = true;
  // wbData.records =[];
  // let param = initParam(1)
  // get_wb(param).then(res=>{
  //   wbData.records =  res.data.data.records
  //   common.pages = res.data.data.pages
  //   common.current = res.data.data.current
  //   if(wbData.records.length >= common.total){
  //     finished.value = true
  //   }else {
  //     finished.value = false
  //   }
  //   isSearch.value = false
  //   search.formShow=false
  //   search.searchNow = false
  //   loading.value = false
  // }).catch(err=>{
  //   search.searchNow = false
  // })

}
const searchWB = ()=>{
  search.searchNow = true;
  finished.value = true;
  wbData.records =[];
  let param = initParam(1)

  get_wb(param).then(res=>{
    wbData.records =  res.data.data.records
    common.pages = res.data.data.pages
    common.current = res.data.data.current
    if(wbData.records.length >= common.total){
      finished.value = true
    }else {
      finished.value = false
    }
    if(search.contnet || search.start || search.end){
      isSearch.value = true
    }else {
      isSearch.value = false
    }
    search.formShow=false
    search.searchNow = false
    loading.value = false
  }).catch(err=>{
    search.searchNow = false
  })

}


const searchRset = ()=>{
  search.contnet =  null
  search.date = null
  search.start =  null
  search.end = null
}

const onClickRight= ()=>{
  search.formShow = !search.formShow;
}
const onClickLeft= ()=>{
  router.push("/addWeibo")
}
const onLoad = () =>{
  let param = initParam(200)

  get_wb(param).then(res=>{
    wbData.records = wbData.records.concat(res.data.data.records)
    common.current = res.data.data.current
    common.total = res.data.data.total
    console.log(wbData.records.length)
    if(wbData.records.length >= common.total){
      finished.value = true
    }
    loading.value = false
  }).catch(err=>{

  })
}


const onRefresh = () => {
  finished.value = false;
  let param = initParam(1)

  get_wb(param).then(res=>{
    wbData.records =  res.data.data.records
    common.pages = res.data.data.pages
    common.current = res.data.data.current
    common.refresh = false
    if(wbData.records.length >= common.total){
      finished.value = true
    }
    loading.value = false
  }).catch(err=>{
    common.refresh = false
  })
};





const onRefreshNE = () => {
  finished.value = false;
  let param = initParam(1)

  get_wb(param).then(res=>{
    wbData.records =  res.data.data.records
    common.pages = res.data.data.pages
    common.current = res.data.data.current
    common.refresh = false
    if(wbData.records.length >= common.total){
      finished.value = true
    }
    loading.value = false
    closeToast();
  }).catch(err=>{
    common.refresh = false
    closeToast();
  })
};

const showMoreInfo = (wbId) =>{
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    loadingType: 'spinner',
  });
  delete_wb({"id" : wbId}).then(res=>{
    onRefreshNE()
  })
}

watch(()=>upLoad.loadingLen,
    ()=>{
       if(upLoad.loadingLen === 100){
         upLoad.loadingShow = false
         showNotify({ type: 'success', message: '发送成功请下拉刷新' });
       }
    })

</script>

<template>

  <van-nav-bar id="titlebar" :fixed="true" title=""
                   @click-left="onClickLeft"
                   @click-right="onClickRight" :placeholder="true">
      <template #left>
        <van-icon name="plus" size="18" />
      </template>
      <template #right>
        <van-icon  v-show="!isSearch" name="search" size="18" />
        <van-button v-show="isSearch" plain  type="primary" size="mini" >筛选中</van-button>
      </template>
    </van-nav-bar>
    <div v-if="upLoad.loadingShow" style="text-align: left;padding: 8px 0 ;color: #5195FF">
      <van-progress :percentage="upLoad.loadingLen" pivot-text="发布中"/>
    </div>

      <transition name="van-slide-down">
          <div v-show="search.formShow" style="margin-bottom: 8px">
            <van-cell-group >
                <van-field  v-model="search.contnet" clearable label="搜索内容" placeholder="请输入搜索内容" />
                <van-field label="选择发布日期"
                           is-link clearable
                           readonly
                           placeholder="点击选择日期"
                           v-model="search.date" @click="search.dateShow = true" />
                <van-calendar v-model:show="search.dateShow" type="range"
                              :min-date="search.minDate" :max-date="search.maxDate"
                              :show-confirm="false"  switch-mode="year-month" @confirm="dateHandle"  />
            </van-cell-group>
            <van-row justify="space-around" style="margin-top: 6px">
              <van-col span="8"> <van-button
                  plain hairline @click="searchWB"
                  loading-text="搜索中..."
                  :loading="search.searchNow"
                  type="primary">搜索</van-button></van-col>
              <van-col span="8"><van-button plain hairline type="success"
                        loading-text="搜索中..."                  :loading="search.searchNow"
                                            @click="searchRsetRefresh">重置</van-button></van-col>
            </van-row>
          </div>
      </transition>

  <van-pull-refresh style="padding: 1px 0;background-color: #efefef" v-model="common.refresh" @refresh="onRefresh" >

      <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
      >
        <van-space direction="vertical" fill size="6px">
            <weibo-info v-for="item in wbData.records" :weibo-record="item"   @show-more = "showMoreInfo"/>
        </van-space>
      </van-list>
    <van-back-top  bottom="70px"/>

  </van-pull-refresh>

</template>

<style>
.van-field__label{
  --van-field-label-color: #787878;
}
.van-field__value{
  --van-field-input-text-color: #787878
}
</style>